import csv
import datetime
from django.shortcuts import render_to_response, get_object_or_404
from django.template import Template,  Context
from django.http import Http404, HttpResponse, HttpResponseRedirect
from nokia.tt.models import *
from django.contrib.contenttypes.models import *
from nokia.reporting.models import *
from django import newforms as forms
from django.template import RequestContext
from django.utils import simplejson
from django.contrib.admin.views.main import ChangeList

TICKET_FIELDS = ('id', 'summary','creation_date','closed_date','within_sla',\
                 'time_open','priority.name','status.name',\
                 'assigned_group.name','res_code.code') 


class ReportError(Exception):
    pass

class NoResultsError(ReportError):
    pass

class FieldError(ReportError):
    def __init__(self,object,field):
        self.field = field
        self.object = object
    def __str__(self):
        return `self.field`

def report_index(request):
	"""Index of all reports"""
	cl = ChangeList(request, Report)
	ec = {
		'title' : 'Report Index',
		'cl' : cl,
	}
	rc = RequestContext(request, ec)
	return render_to_response('reporting/index.html', rc)

def report_to_csv(request,id,qs=None):
    report = Report.objects.get(id=id)
    if not qs:
        qs = report.model.objects.all()
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = \
            'attachment; filename=report_%s.csv' % report.title
    w = csv.writer(response)
    for row in report.get_report()(qs):
        w.writerow(row)

    return response

    
def build_report(request):
    """Create a new report"""
    FIELDS = ('title','description','type')
    user = request.user
    ReportForm = forms.form_for_model(Report)#, fields=FIELDS)
    if request.method == 'POST':
	data = request.POST.copy()
	data.update({'user':user.id})
        form = forms.form_for_model(Report)(data)
        #form = forms.form_for_model(Report, fields=FIELDS+('user',))(data)
	if form.is_valid():
	    report = form.save()
	    return HttpResponseRedirect('/reports/%s' % report.id)
    else:
        form = ReportForm()
    rc = RequestContext(request,{
          'form': form,
				 })
    return render_to_response('reporting/create.html',rc)
    
def report_details(request,id,example_length=5):
    """Information page for a report"""
    report = get_object_or_404(Report,id=id)
    #build the header row


    rc = RequestContext(request,{
	    'report': report,
		'count': report.model.objects.count(),
				 })
    return render_to_response('reporting/details.html',rc)


